package com.canal.collection.service.impl;

import com.canal.collection.config.CollectionProperties;
import com.canal.collection.entity.*;
import com.canal.collection.exception.BuzException;
import com.canal.collection.repository.*;
import com.canal.collection.service.DataCollectionService;
import com.canal.collection.service.MessageService;
import com.canal.collection.transfer.req.RegReq;
import com.canal.collection.transfer.req.VisitReq;
import com.canal.collection.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author yangbo
 * @date 2020-07-02 14:22
 */
@Service
@Slf4j
public class DataCollectionServiceImpl implements DataCollectionService {

    /**
     * 不能再次发送的手机
     */
    private static final String CANT_TELE_PREFIX = "canal_cant_phone:";

    private static final String SMS_CODE = "canal_sms_code:";

    private static final String PASSWORD = "123456";

    private static List<String> names = new ArrayList<>();

    static {
        names.add("挖财");
        names.add("富贵");
        names.add("来财");
        names.add("好运");
        names.add("赚赚");
    }
    @Autowired
    private CollectionProperties collectionProperties;

    @Autowired
    private ChannelItemRepository channelItemRepository;

    @Autowired
    private RtDataRepository rtDataRepository;

    @Autowired
    private CashUserRepository cashUserRepository;

    @Autowired
    private MessageService messageService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CashUserLoginRepository cashUserLoginRepository;

    @Autowired
    private RtRegRepository rtRegRepository;

    /**
     * 获取渠道号id
     * @param code
     * @return
     */
    @Override
    public Integer itemId(String code) {
        ChannelItem channelItem = channelItemRepository.findByCode(code);
        if(channelItem == null) {
            return null;
        }
        return channelItem.getId();
    }

    @Override
    public void pvUv(VisitReq visitReq) {
        RtData rtData = new RtData();
        ChannelItem channelItem = new ChannelItem();
        channelItem.setId(visitReq.getChannelItem());
        rtData.setChannelItem(channelItem);
        rtData.setIp(visitReq.getIp());
        rtData.setDistrict(visitReq.getDistrict());
        rtData.setDeviceName(visitReq.getDeviceName());
        rtData.setUa(visitReq.getUa());
        rtDataRepository.save(rtData);
    }

    @Override
    public boolean existPhone(String phone) {
        CashUser cashUser = cashUserRepository.findByPhone(phone.trim());
        if(cashUser != null) {
            return true;
        }
        RtReg rtReg = rtRegRepository.findByPhone(phone.trim());
        if(rtReg != null) {
            return true;
        }
        return false;
    }

    @Override
    public void sendSms(String tele, String code) throws BuzException {
        //发送
        messageService.sendMessage(tele,code);
        //缓存code和手机号
        String cantKey = CANT_TELE_PREFIX + tele;
        String smsKey = SMS_CODE + tele;
        redisTemplate.opsForValue().set(cantKey,"",1, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(smsKey,code,5,TimeUnit.MINUTES);
    }

    @Override
    public boolean canSend(String phone) {
        String key = CANT_TELE_PREFIX + phone;
        return redisTemplate.hasKey(key);
    }

    /**
     * 用户注册
     * @param regReq
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String regUser(RegReq regReq) throws BuzException {
        //校验短信验证码
        String key = SMS_CODE + regReq.getPhone();
        String code = redisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(code)) {
            throw new BuzException(501,"短信验证码已失效");
        }
        if(!regReq.getCode().equals(code)) {
            throw new BuzException(502,"短信验证码不正确");
        }
        //通过之后清除验证码
        redisTemplate.delete(key);
        //保存用户cashUser和cashUserLogin
//        CashUserLogin userLogin = new CashUserLogin();
//        userLogin.setPassword(MD5Util.encrypt(PASSWORD));
//        userLogin.setUserFlag(1L);
//        userLogin.setPhone(regReq.getPhone());
//        userLogin.setIp(regReq.getIp());
//        userLogin.setCreateTime(new Date());
//        userLogin.setModifyTime(new Date());
//        cashUserLoginRepository.save(userLogin);
//        CashUser cashUser = new CashUser();
//        cashUser.setPhone(regReq.getPhone());
//        Random random = new Random();
//        int index = random.nextInt(names.size());
//        cashUser.setNickName(names.get(index % names.size()) + regReq.getPhone().substring(7, 11));
        //查询渠道号
        Optional<ChannelItem> channelItemOptional = channelItemRepository
                .findById(regReq.getChannelId());
        ChannelItem channelItem = channelItemOptional.get();
//        cashUser.setRegFrom(channelItem.getName());
//        cashUser.setChannelId(channelItem.getId());
//        cashUser.setUserId(userLogin.getId());
//        cashUser.setCreateTime(new Date());
//        cashUser.setModifyTime(new Date());
//        cashUserRepository.save(cashUser);
        // 记录注册信息
        if(rtRegRepository.findByPhone(regReq.getPhone().trim()) != null) {
            return collectionProperties.getApkDomain() + channelItem.getApkUrl();
        }
        RtReg rtReg = new RtReg();
        rtReg.setChannelItem(channelItem);
        rtReg.setIp(regReq.getIp());
        rtReg.setPhone(regReq.getPhone());
        rtRegRepository.save(rtReg);
        //获得下载apk的路径
        return collectionProperties.getApkDomain() + channelItem.getApkUrl();
    }

    /**
     * 得到渠道的apkUrl
     * @param channelId
     * @return
     * @throws BuzException
     */
    @Override
    public String getApkUrl(Integer channelId) {
        //查询渠道号
        Optional<ChannelItem> channelItemOptional = channelItemRepository
                .findById(channelId);
        if(channelItemOptional.isPresent()) {
            ChannelItem channelItem = channelItemOptional.get();
            return collectionProperties.getApkDomain() + channelItem.getApkUrl();
        }
        return "";
    }
}
